﻿
using System;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;

namespace Bronze.XXT.PhoneServer
{
	/// <summary>
	/// Description of PublicMethod.
	/// </summary>
	public class Utility
	{
		public static bool IsNum(string strValue,bool allowNull)
		{
			string pattern = "^\\d+$";
            if (string.IsNullOrEmpty(strValue))
            {
                return allowNull;
            }
            return Regex.IsMatch(strValue, pattern);
		}

        #region

        //public static String Decode(Byte[] buf, int StartIndex, int Length, CODING Coding)
        //{
        //    String str = String.Empty;
        //    if (Coding == CODING.ASCII)
        //        str = System.Text.Encoding.ASCII.GetString(buf, StartIndex, Length);

        //    else if (Coding == CODING.UCS2)
        //        str = System.Text.Encoding.BigEndianUnicode.GetString(buf, StartIndex, Length);
        //    else if (Coding == CODING.GBK)
        //        str = System.Text.UnicodeEncoding.GetEncoding("gb2312").GetString(buf, StartIndex, Length);
        //    return str;
        //}
        //public static Byte[] Encode(String str, CODING coding)
        //{
        //    Byte[] buf = null;
        //    if (str == null)
        //        return buf;
        //    if (coding == CODING.ASCII)
        //        buf = System.Text.Encoding.ASCII.GetBytes(str);
        //    else if (coding == CODING.UCS2)
        //        buf = System.Text.Encoding.BigEndianUnicode.GetBytes(str);
        //    else if (coding == CODING.GBK)
        //        buf = System.Text.UnicodeEncoding.GetEncoding("gb2312").GetBytes(str);

        //    return buf;

        //}
        //public static UInt32 CountLength(String str, CODING coding)
        //{
        //    Byte[] buf = Encode(str, coding);
        //    if (buf != null)
        //        return (UInt32)buf.Length;
        //    else
        //        return 0;
        //}

        public static Byte[] IntToNetBytes(object obj)
        {
            Byte[] bytes = null;
            if (obj.GetType() == System.Type.GetType("System.UInt32"))
            {
                UInt32 val = (UInt32)obj;
                bytes = BitConverter.GetBytes(val);
            }
            if (obj.GetType() == System.Type.GetType("System.UInt64"))
            {
                UInt64 val = (UInt64)obj;
                bytes = BitConverter.GetBytes(val);
            }
            if (obj.GetType() == System.Type.GetType("System.Byte"))
            {
                Byte val = (Byte)obj;
                bytes = BitConverter.GetBytes(val);
            }

            if (bytes != null)
                System.Array.Reverse(bytes);

            return bytes;

        }
        public static object NetBytesToInt(Byte[] bytes, int index, int length)
        {
            Array.Reverse(bytes, index, length);
            if (length == 1)
            {
                return (UInt32)bytes[index];
            }

            else if (length == 4)
                return BitConverter.ToUInt32(bytes, index);
            else if (length == 8)
                return BitConverter.ToUInt64(bytes, index);
            else
                return 0;
        }

        /// <summary>
        /// 将src里的字节与add里的从start开始到end（不包括第end个位置)的字节串连在一起返回
        /// </summary>
        /// <param name="src"></param>
        /// <param name="add"></param>
        /// <param name="start">add 开始位置</param>
        /// <param name="end">add 的结束位置(不包括end位置)</param>
        /// <returns>也即实现类似String类型的src+add.subString(start,end)功能</returns>
        public static byte[] byteAdd(byte[] src, byte[] add, int start, int end)
        {
            byte[] dst = new byte[src.Length + end - start];
            for (int i = 0; i < src.Length; i++)
            {
                dst[i] = src[i];
            }
            for (int i = 0; i < end - start; i++)
            {
                dst[src.Length + i] = add[start + i];
            }
            return dst;
        }

        public static string GetTimestampString(DateTime time)
        {
            return time.ToString("MMddHHmmss");
        }

        #endregion

        /// <summary>
        /// 设置MessageBody类型的缓存
        /// </summary>
        public static void SetTypeCache() 
        {
            MsgAttribute attr = null;
            string strKey = string.Empty;

            var types = Assembly.GetExecutingAssembly().GetTypes();
            var baseType = typeof(MessageBody);

            ProgramCache.MESSAGEBODY_TYPES_CACHE.Clear();

            foreach (Type type in types)
            {
                if (baseType.IsAssignableFrom(type))
                {
                    var attrs = type.GetCustomAttributes(typeof(MsgAttribute), false);
                    if (attrs != null && attrs.Any()) 
                    {
                        attr = attrs[0] as MsgAttribute;
                    }
                    if (attr != null) 
                    {
                        strKey = attr.func_no + Convert.ToInt16(attr.isRequest).ToString();
                        if (!ProgramCache.MESSAGEBODY_TYPES_CACHE.ContainsKey(strKey)) 
                        {
                            ProgramCache.MESSAGEBODY_TYPES_CACHE.Add(strKey, type);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 计算一个字符串的长度，包括中文的情况
        /// </summary>
        /// <param name="param">操作的字符串</param>
        /// <returns></returns>
        public static int GetStringLength(string param)
        {
            ASCIIEncoding n = new ASCIIEncoding();
            byte[] b = n.GetBytes(param);
            int l = 0;  // l 为字符串之实际长度
            for (int i = 0; i <= b.Length - 1; i++)
            {
                if (b[i] == 63)  //判断是否为汉字或全脚符号
                {
                    l++;
                }
                l++;
            }
            return l;
        }


        //public static byte[] GetIntByte(int data,int maxLength)
        //{
        //    System.Text.Encoding.Default.GetBytes(data.ToString(),)
        //}

        public static void WiteBytesToFile(string fileName, byte[] bytes) 
        {
            string strPath = string.Format(@"d:\data\{0}",fileName);
            using (FileStream fs = new FileStream(strPath, FileMode.Create))
            {
                try
                {
                    fs.Write(bytes, 0, bytes.Length);
                    
                }
                finally 
                {
                    fs.Close();
                }
            }
        }

        public static byte[] ReadBytesFormFile(string fileName) 
        {
            //string strPath = string.Format("~/{0}", fileName);
            string strPath = string.Format(@"d:\data\{0}", fileName);
            FileInfo fi = new FileInfo(strPath);
            byte[] buffer = new byte[fi.Length];
            using (FileStream fs = new FileStream(strPath, FileMode.Open))
            {
                try
                {
                    fs.Read(buffer, 0, buffer.Length);
                }
                finally
                {
                    fs.Close();
                }
            }
            return buffer;
        }

        public static string BytesToString(byte[] bytes)
        {
            return Convert.ToBase64String(bytes);
        }

        public static byte[] StringToBytes(string base64String)
        {
            return Convert.FromBase64String(base64String);
        }

        public static string ConvertCardID(string hexCardId)
        {
            try
            {
                var id = Convert.ToInt32(hexCardId.Trim(), 16);
                return id.ToString().PadLeft(10, '0');
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
